<template>
  <el-card>
    <div class="head-container">
      <el-input
        v-model="searchText"
        placeholder="请输入部门名称"
        clearable
        size="small"
        prefix-icon="el-icon-search"
        style="margin-bottom: 20px"
      />
    </div>
    <div>
      <el-radio-group v-model="seltype" size="small">
        <el-radio-button label="river">河流</el-radio-button>
        <el-radio-button label="region">行政区划</el-radio-button>
        <!-- <el-radio-button label="水源地级别"></el-radio-button> -->
      </el-radio-group>
    </div>
    <div class="head-container">
      <el-tree
        :data="deptOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        show-checkbox
        default-expand-all
        ref="tree"
        node-key="id"
        highlight-current
        @node-click="handleNodeClick"
        @check-change="handleCheckChange"
        @check="handleCheck"
      />
    </div>
  </el-card>
</template>

<script>
import { getLakeSegmentTree, getRegionTree } from "@/api/dataResources/common";
export default {
  name: "TreeSelect",
  data() {
    return {
      searchText: "",
      seltype: "river",
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  watch: {
    searchText(val) {
      this.$refs.tree.filter(val);
    },
    seltype: {
      handler(newVal) {
        if (newVal === "river") {
          this.getRiverTree();
        } else if (newVal === "region") {
          this.getRegionTree();
        }
      },
      immediate: true, // 初始化时也会执行
    },
  },
  created() {
    // this.getRegionTree();
    // this.getRiverTree();
  },
  methods: {
    // 节点过滤方法
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 将扁平数据转换为树形结构
    convertToTree(data) {
      // 创建id到节点的映射表
      const nodeMap = {};

      // 初始化所有节点，保留原有id，添加label和children
      data.forEach((node) => {
        nodeMap[node.id] = {
          ...node, // 保留所有原始字段（包括id）
          label: node.name, // 添加label字段，值为name
          children: [], // 初始化子节点数组
        };
      });

      // 构建树形结构
      const tree = [];
      data.forEach((node) => {
        const currentNode = nodeMap[node.id];
        const parentNode = nodeMap[node.pId];

        if (parentNode) {
          // 存在父节点，添加到父节点的children中
          parentNode.children.push(currentNode);
        } else {
          // 根节点（pId为0）直接加入树
          tree.push(currentNode);
        }
      });

      return tree;
    },
    // 获取区划
    getRegionTree() {
      getRegionTree().then((res) => {
        if (res.code === 200) {
          this.deptOptions = this.convertToTree(res.data || []);
        }
      });
    },
    //获取河流树
    getRiverTree() {
      getLakeSegmentTree().then((res) => {
        if (res.code === 200) {
          this.deptOptions = this.convertToTree(res.data || []);
        }
      });
    },

    // 点击节点时触发
    handleNodeClick(data, node) {
      // console.log("点击的节点数据：", data);
      // console.log("节点实例：", node);
    },

    // 节点勾选状态变化时触发
    handleCheckChange(data, checked, indeterminate) {
      // console.log("节点数据：", data);
      // console.log("是否勾选：", checked);
      // console.log("是否半选：", indeterminate);
    },

    // 节点勾选事件（包含全选/半选状态）
    handleCheck(selection, checkedKeys) {
      console.log("当前选中的节点数组：", selection);
      console.log("当前选中的节点ID数组：", checkedKeys);
      // this.selectedNodes = selection; // 保存选中的节点
      const ids = checkedKeys.checkedNodes.map((node) => node.id).join(",");
      this.$emit("node-click", ids);
    },
  },
};
</script>

<style></style>
